package com.easyjoin.config;

import com.easyjoin.annotation.EasyJoinOne;
import com.easyjoin.annotation.EasyJoinList;
import com.easyjoin.core.EasyForeignListPropertyWriter;
import com.easyjoin.core.EasyForeignPropertyWriter;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

public class EasyForeignBeanSerializerModifier extends BeanSerializerModifier {

    private final DataSource dataSource;
    public EasyForeignBeanSerializerModifier( DataSource dataSource) {
        this.dataSource = dataSource;
    }
    @Override
    public List<BeanPropertyWriter> changeProperties(
            SerializationConfig config,
            BeanDescription beanDesc,
            List<BeanPropertyWriter> beanProperties) {

        List<BeanPropertyWriter> newWriters = new ArrayList<>();
        for (BeanPropertyWriter writer : beanProperties) {
            EasyJoinOne ann = writer.getAnnotation(EasyJoinOne.class);
            EasyJoinList annList = writer.getAnnotation(EasyJoinList.class);
            if (ann != null) {
                // 序列化时，判断带有 EasyForeignKeyToValue 注解的字段，使用自定义 writer 替换
                newWriters.add(new EasyForeignPropertyWriter(writer, ann.joinColumn(),ann.selectColumns(),ann.tableName(),ann.cache(), dataSource));
            } else if (annList != null) {
                // 序列化时，判断带有 EasyForeignKeyToList 注解的字段，使用自定义 writer 替换
                newWriters.add(new EasyForeignListPropertyWriter(writer, annList.joinColumn(),annList.selectColumns(),annList.tableName(),annList.cache(),annList.listAlias(), dataSource));
            } else {
                newWriters.add(writer);
            }
        }
        return newWriters;
    }
}
